package compilarclassejava;

import java.io.File;
import java.util.Arrays;
import java.util.Locale;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class CompilaClasses 
{
	public static boolean compilarClasse(String diretorioArquivoJavaParaCompilar, String urlCompiladorJava)
	{
		try
		{
			/*Java source files read from file system*/
			File []files = new File[]{new File(diretorioArquivoJavaParaCompilar)} ;
			System.setProperty("java.home", urlCompiladorJava);
			JavaCompiler compiladorJava = ToolProvider.getSystemJavaCompiler();
			
			   DiagnosticCollector<JavaFileObject> diagnostics =
			       new DiagnosticCollector<JavaFileObject>();
			StandardJavaFileManager stdFileManager = compiladorJava.getStandardFileManager(diagnostics, Locale.getDefault(), null);
			Iterable<? extends JavaFileObject> unidadesParaCompilar =
					stdFileManager.getJavaFileObjectsFromFiles(Arrays.asList(files));
			/*Create a compilation task from compiler by passing in the required input objects prepared above*/
			CompilationTask tarefaDoCompilador = compiladorJava.getTask(null, stdFileManager, diagnostics, null, null, unidadesParaCompilar) ;
			boolean statusCompilacao = tarefaDoCompilador.call();
			if (!statusCompilacao){//If compilation error occurs
			    /*Iterate through each compilation problem and print it*/
			    for (@SuppressWarnings("rawtypes") Diagnostic diagnostic : diagnostics.getDiagnostics()){
			        System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
			    }
			}
			
	        stdFileManager.close() ;//Close the file manager
			
			
			System.out.println("compilacao bemm sucedida");
			return statusCompilacao;
		}
		catch(Exception e)
		{
			//qualquer excecao significa que a compilacao nao foi bem sucedida
			return false;
		}
		
	}
	public static void main(String args[])
	{
		
		boolean resultadoCompilacao = compilarClasse("C:/Users/joao/Documents/eclipse new projets/TestBoot/src/testes/Teste.java", "C:\\Program Files\\Java\\jdk1.7.0_03");
		System.out.println("compilou bem:" + resultadoCompilacao);
	}

}
